package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.Neusoft.vo.SalaryGroupVo;
import com.zhangtai.config.AsyncEmployeeMethod;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.UserDao;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dto.*;
import com.zhangtai.modules.entity.common.Nativeplace;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.security.SecurityEntity;
import com.zhangtai.modules.entity.security.SecurityItemEntity;
import com.zhangtai.modules.entity.system.UserEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.R;
import com.zhangtai.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("job")
@RestController
@Slf4j
@Api(tags = "岗位接口")
public class JobController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AsyncEmployeeMethod asyncEmployeeMethod;
    @Autowired
    BaseMssqlServiceImpl jobService;
    //    @Autowired
//    JobDaoMssql jobDaoMssql;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private LoginController loginController;




    public Map<Long,String> jobMap = null;
    public Map<Long,String> orgMap = null;

    public Map<Long,String> jobLevelMap = null;
    public Map<Long,String> jobLevelCodeMap = null;
    public Map<Long,JobLevelDto> jobLevelEntityMap = null;
    public Map<Long,String> systemMap=null;  //体系
    public Map<Long,String> lineMap=null; //条线

    public Map<Long,Map<Integer, SecurityItemEntity>> securityMap = null;
    public Map<Long, SecurityEntity> sMap = null;

    public Map<String,String> nationality=null;
    public Map<Long,String> nativeplace=null;
    public Map<Long,List<Long>> orgAllChildrenMap = new HashMap<>();
    public Map<Long, SalaryGroupDto> salaryGroupDtoMap=new HashMap<>();
    public Map<Long, SalaryGroupVo> salaryGroupVoMap=new HashMap<>();

    public Map<String,Long> jobLevel=new HashMap<>(); //职级 <String ，Long>  格式
    public Map<String,List<SalaryGroupDto>> salaryGroupMap=new HashMap<>();

    public Map<Long, SalaryPayrollUnitDto> SalaryPayrollUnitMap=new HashMap<>();

    public Map<String,String> company = new HashMap<>();

    @GetMapping("/findJobByOrgId/{orgId}")
    @ApiOperation(value="根据部门id查找职位")
    public R<List<JobDto>> findJobByOrgId(@PathVariable("orgId") Long orgId){
        List<JobDto> jobEntities = jobService.findJobByKeyword(orgId);
        return R.ok(jobEntities);

    }

//    @GetMapping("/findTiaoxinTixiByJobId/{id}")
//    @ApiOperation(value="根据岗位id查找条线和体系")
//    public R<JSONObject> findTiaoxinTixiByJobId(@PathVariable Long id){
//        JSONObject tiaoxianTixiByJobId = jobDaoMssql.getTiaoxianTixiByJobId(id);
//        return R.ok(tiaoxianTixiByJobId);
//    }

    @GetMapping("/getBaseItem")
    @ApiOperation(value="获取籍贯树、组织机构树、职级、条线、体系、招聘网站")
    public R<JSONObject> getBase(){
        Object o = redisTemplate.boundHashOps("GETBASEITEM").get("item");

        return R.ok(o);



    }

    @GetMapping("/getNativeplace")
    @ApiOperation(value="单独获取籍贯")
    public R<List<Map<String, Object>>> getNativeplace(){


        Object o = redisTemplate.boundHashOps("getNativeplace").get("nativeplace");
        if (!ObjectUtils.isEmpty(o)){
            return R.ok(o);
        }

        List<Nativeplace> allNativePlace = jobService.findAllNativeplace();
        List<Map<String, Object>> nativePlace = jobService.findNativePlaceByPid(allNativePlace, -1l);

        redisTemplate.boundHashOps("getNativeplace").put("nativeplace",nativePlace);
//        redisTemplate.expire("getNativeplace",48,TimeUnit.HOURS);
        return R.ok(nativePlace);
    }



    @GetMapping("/findEmpByNameOrCode")
    @ApiOperation(value="根据名字或工号查询员工-去两个库查")
    public R<ArrayList<EmployeeInfoDto>> findEmpByName(@RequestParam(value = "isOrgGroupFilter",defaultValue = "false") Boolean isOrgGroupFilter,
                                                       @RequestParam(value = "name",required = false) String name,
                                                       @RequestParam(value = "isDismiss",required = false) Boolean isDismiss,
                                                       @RequestParam(value = "code",required = false) String code, HttpServletRequest request) throws Exception {

        List<EmployeeInfoEntity> empByCodeFromMssql  = new ArrayList<>();
        List<EmployeeInfoEntity> entities;
        if(isOrgGroupFilter){

            R checkR = loginController.checkOrgPermission(request,null,false);
            if(!R.isOk.equals(checkR.getStatus())){
                return checkR;
            }
            List<Long> orgIds = (List<Long>) checkR.getData();
//            empByCodeFromMssql= jobDaoMssql.findEmpByCodeFromMssql(orgIds,name, code,isDismiss);
            entities = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>()
                    .in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds)
                    .eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)
                    .like(!StringUtils.isEmpty(name), "name", name)
                    .eq(!StringUtils.isEmpty(code), "code", code)
                    .ne(!isDismiss, "employeestatus", 3)
                    .eq("is_delete","0"));
        }else {
//            empByCodeFromMssql= jobDaoMssql.findEmpByCodeFromMssql(null,name, code,isDismiss);
            entities = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().like(!StringUtils.isEmpty(name), "name", name)
                    .eq(!StringUtils.isEmpty(code), "code", code)
                    .ne(!isDismiss, "employeestatus", 3)
                    .eq("is_delete","0"));
        }

        if (CollectionUtils.isEmpty(empByCodeFromMssql)&&CollectionUtils.isEmpty(entities)){
            return R.ok();
        }

        ArrayList<String> idCardList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(entities)){
            for (EmployeeInfoEntity entity : entities) {
                idCardList.add(entity.getIdcard());
            }

        }
        ArrayList<EmployeeInfoEntity> employeeInfoEntities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(empByCodeFromMssql)){
            for (EmployeeInfoEntity employeeInfoEntity : empByCodeFromMssql) {
                String idCard = employeeInfoEntity.getIdcard();
                setJobLevel(employeeInfoEntity); //封装职级
                //            去重
                if (!idCardList.contains(idCard)){
                    employeeInfoEntities.add(employeeInfoEntity);
                }
            }
        }
//        //在本地库没有则插入
        asyncEmployeeMethod.saveEhrEmployee(employeeInfoEntities);
        entities.addAll(employeeInfoEntities);  //本地库 和 sqlServer数据合并
        ArrayList<EmployeeInfoDto> employeeInfoDtos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(entities)){
            for (EmployeeInfoEntity entity : entities) {
                EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(entity, EmployeeInfoDto.class);
                Long orgId = entity.getOrgId();
                String orgNameById = getOrgNameById(orgId);
                employeeInfoDto.setOrgname(orgNameById); //公司名
                Long unitId = entity.getUnitId();
                String unitName = getOrgNameById(unitId);
                employeeInfoDto.setUnitname(unitName); //部门名
                Long jobId = entity.getJobId();
                String jobName = getJobName(jobId);
                employeeInfoDto.setJobname(jobName); //岗位名
                employeeInfoDtos.add(employeeInfoDto);
            }
        }
        return R.ok(employeeInfoDtos);
    }

    private void setJobLevel(EmployeeInfoEntity employeeInfoEntity) {
        Long managementJoblevelId = employeeInfoEntity.getManagementJoblevelId();
        Long professionJoblevelId = employeeInfoEntity.getProfessionJoblevelId();
        if (managementJoblevelId!=null){
            employeeInfoEntity.setJobLevelType(2);
            employeeInfoEntity.setJobLevelId(managementJoblevelId);
        }else {
            employeeInfoEntity.setJobLevelType(1);
            employeeInfoEntity.setJobLevelId(professionJoblevelId);
        }
    }


    @GetMapping("/findEmpByAccount")
    @ApiOperation(value="根据账号去sqlServer查询员工")
    public R<EmployeeInfoEntity> findEmpByAccount(@RequestParam(value = "account") String account){



        EmployeeInfoEntity employeeInfoEntity = new EmployeeInfoEntity();
//                employeeInfoEntity = jobDaoMssql.findEmpByAccount(account);
        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.ok();
        }


//        封装职级
        setJobLeVel(employeeInfoEntity);


        return R.ok(employeeInfoEntity);
    }

    @GetMapping("/findReAndPu")
    @ApiOperation(value="查询所有奖惩类型")
    public R<List<JSONObject>> findReAndPu(){
        List<JSONObject> reAndPu = new ArrayList<>();
//        reAndPu = jobDaoMssql.findReAndPu();
        return R.ok(reAndPu);
    }


    //
    @PostMapping("/getEmpByUnitId")
    @ApiOperation(value="根据部门id查询员工-去两个库查")
    public R<ArrayList<EmployeeInfoDto>> getEmpByUnitId(@RequestParam("ids") List<Long> ids) throws Exception {
        if (CollectionUtils.isEmpty(ids)){
            return R.ok();
        }

        List<EmployeeInfoEntity> empByCodeFromMssql =new ArrayList<>() ;
        List<EmployeeInfoEntity> entities;

//            empByCodeFromMssql= jobDaoMssql.findEmpByUnitIds(ids);
        entities = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().in("unit_id",ids).eq("is_delete",0));


        if (CollectionUtils.isEmpty(empByCodeFromMssql)&&CollectionUtils.isEmpty(entities)){
            return R.ok();
        }

        ArrayList<Long> entitiesLongs = new ArrayList<>();
        if (!CollectionUtils.isEmpty(entities)){
            for (EmployeeInfoEntity entity : entities) {
                entitiesLongs.add(entity.getOid());
            }

        }
        ArrayList<EmployeeInfoEntity> employeeInfoEntities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(empByCodeFromMssql)){
            for (EmployeeInfoEntity employeeInfoEntity : empByCodeFromMssql) {
                Long oid = employeeInfoEntity.getOid();
                setJobLevel(employeeInfoEntity); //封装职级
                //            去重
                if (!entitiesLongs.contains(oid)){
                    employeeInfoEntities.add(employeeInfoEntity);
                }
            }
        }
//        //在本地库没有则插入
//        asyncEmployeeMethod.saveEhrEmployee(employeeInfoEntities);
        entities.addAll(employeeInfoEntities);  //本地库 和 sqlServer数据合并
        ArrayList<EmployeeInfoDto> employeeInfoDtos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(entities)){
            for (EmployeeInfoEntity entity : entities) {
                EmployeeInfoDto employeeInfoDto = BeanUtilsMabach.doToDto(entity, EmployeeInfoDto.class);
                Long orgId = entity.getOrgId();
                String orgNameById = getOrgNameById(orgId);
                employeeInfoDto.setOrgname(orgNameById); //公司名
                Long unitId = entity.getUnitId();
                String unitName = getOrgNameById(unitId);
                employeeInfoDto.setUnitname(unitName); //部门名
                Long jobId = entity.getJobId();
                String jobName = getJobName(jobId);
                employeeInfoDto.setJobname(jobName); //岗位名
                employeeInfoDtos.add(employeeInfoDto);
            }
        }
        return R.ok(employeeInfoDtos);
    }



    private void setJobLeVel(EmployeeInfoEntity employeeInfoEntity) {
        Long p = employeeInfoEntity.getProfessionJoblevelId();
        Long m = employeeInfoEntity.getManagementJoblevelId();
        if (m!=null){
            employeeInfoEntity.setJobLevelType(2);
            employeeInfoEntity.setJobLevelId(m);
        }else {
            employeeInfoEntity.setJobLevelType(1);
            employeeInfoEntity.setJobLevelId(p);
        }
    }

    /**
     * 根据组织机构id查询名称
     * @param id
     * @return
     */
    public String getOrgNameById(Long id){
//        HashMap<Long, String> orgMap = (HashMap<Long, String>) redisTemplate.boundHashOps(CommonConstr.ORG_MAP).get(CommonConstr.ORG_ITEM);
        String orgName = orgMap.get(id);
        return orgName;
    }

    /**
     * 根据id查找岗位名称
     * @param id
     * @return
     */
    public String getJobName(Long id){
//        HashMap<Long, String> jobMap = (HashMap<Long, String>) redisTemplate.boundHashOps(CommonConstr.JOB_MAP).get(CommonConstr.JOB_ITEM);
        String jobName = jobMap.get(id);
        return jobName;
    }

    /**
     * 根据id查找职级名称
     * @param id
     * @return
     */
    public String getJobLevelNameById(Long id){
//        HashMap<Long, String> jobLevelMap = (HashMap<Long, String>) redisTemplate.boundHashOps(CommonConstr.JOB_LEVEL_MAP).get(CommonConstr.JOB_LEVEL_ITEM);
        String jobLevelName = jobLevelMap.get(id);
        return jobLevelName;
    }

    /**
     * 根据id查找体系
     * @param id
     * @return
     */
    public String getSystemNameById(Long id){

        String systemMapName = systemMap.get(id);
        return systemMapName;
    }


    /**
     * 民族
     * @param id
     * @return
     */
    public String getNationality(String id){
        String s = nationality.get(id);
        return s;
    }

    /**
     * 代缴省市
     * @param id
     * @return
     */
    public String getPaycity(Long id){
        String s = nativeplace.get(id);
        return s;
    }

    /**
     * 根据id查找条线
     * @param id
     * @return
     */
    public String getLineNameById(Long id){

        String systemMapName = lineMap.get(id);
        return systemMapName;
    }

    @PostMapping("/getUnitByName")
    @ApiModelProperty("通过部门名称获取部门信息")
    public R getUnitByName(String name){

//        jobDaoMssql.findJobIdByJobName(name);
        return R.ok();
    }


    @Autowired
    private UserDao userDao;

    /**
     *项目启动前 同步所有用户菜单
     */
    public void getMenu(){

        List<UserEntity> userEntities = userDao.selectList(null);
        for (UserEntity userEntity : userEntities) {
            Long id = userEntity.getUserId();
            List<String> menuByUserId = userDao.findMenuByUserId(id);
            HashSet<String> hashSet = new HashSet<>();
            if (!CollectionUtils.isEmpty(menuByUserId)){
                for (String s : menuByUserId) {
                    if (!com.alibaba.druid.util.StringUtils.isEmpty(s)){
                        hashSet.add(s);
                    }
                }
            }
            redisTemplate.boundValueOps("userMenu"+id).set(hashSet);

        }

    }
    /**
     * 项目启动前 同步所有员工信息到redis
     */
    public void getEmpInfoToRedis(){
        List<EmployeeInfoEntity> employeeInfoEntities = employeeInfoDao.selectList(null);
        for (EmployeeInfoEntity employeeInfoEntity : employeeInfoEntities) {
            String code = employeeInfoEntity.getCode();
            EmployeeCachDto employeeCachDto = BeanUtilsMabach.doToDto(employeeInfoEntity, EmployeeCachDto.class);
            redisTemplate.boundValueOps("employeeInfo"+code).set(employeeCachDto);
        }
    }
















}
